package org.wdj.jpa.service;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.wdj.jpa.MyResponse;
import org.wdj.jpa.entity.SysUser;
import org.wdj.jpa.repository.SysUserRepository;

import javax.annotation.Resource;
import java.util.List;

@Service
public class SysUserService {
    @Resource
    private SysUserRepository sysUserRepository;

    //保存一条记录
    public MyResponse save(SysUser sysUser) {
        try {
            sysUserRepository.save(sysUser);
            return new MyResponse("success", "新增成功");
        } catch (Exception e) {
            return new MyResponse("error", e.getMessage());
        }
    }

    public SysUser find(@RequestBody String username) {
        return sysUserRepository.findByUsername(username);
    }

    //更新用户数据
    public MyResponse update(SysUser sysUser) {
        try {
            SysUser oldSysUser = sysUserRepository.findByUsername(sysUser.getUsername());
            sysUser.setUserId(oldSysUser.getUserId());
            sysUserRepository.save(sysUser);
            return new MyResponse("success", "更新成功");
        }catch (Exception e) {
            return new MyResponse("error", e.getMessage());
        }
    }

    //删除记录
    public MyResponse delete(String username) {
        try {
            SysUser oldSysUser = sysUserRepository.findByUsername(username);
            sysUserRepository.delete(oldSysUser);
            return new MyResponse("success", "delete success");
        } catch (Exception e) {
            return new MyResponse("error", e.getMessage());
        }
    }

    //save all record
    public MyResponse saveAll(List<SysUser> sysUserList) {
        try {
            sysUserRepository.saveAll(sysUserList);
            return new MyResponse("success", "bucket add successful");
        } catch (Exception e) {
            return new MyResponse("error", e.getMessage());
        }
    }

    public List<SysUser> list() {
        return sysUserRepository.findAll();
    }

    //分页
    public Page<SysUser> page(Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.ASC, "userId");
        return sysUserRepository.findAll(pageable);
    }

    //自宝义搜索
    public Page<SysUser> searchByNickname(String nickname, Integer page, Integer size) {
        Pageable pageable = PageRequest.of(page, size, Sort.Direction.ASC, "userId");
        return sysUserRepository.searchByNickname(nickname, pageable);
    }
}
